package com.b510.test.iqiyi;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.b510.bean.Person;
import com.b510.service.PersonService;
import com.svo.util.HttpUtils;

import us.codecraft.xsoup.Xsoup;

public class IqiyiDianshiju {
    private static PersonService personService;
	private Person person;
	public static void main(String[] args) {
        ApplicationContext act = new ClassPathXmlApplicationContext("bean.xml");
        personService = (PersonService) act.getBean("personService");
        new IqiyiDianshiju().start();
    }
    public void start() {
        int totalPage = 50;
        String listUrl = "https://pcw-api.iqiyi.com/search/recommend/list?channel_id=2&data_type=1&mode=24&page_id=1&ret_num=48";
        for (int i = 1; i <= totalPage; i++) {
            try {
                String reqUrl = listUrl.replace("page_id=1","page_id="+i);
                String json = HttpUtils.get(reqUrl,"");
                JSONObject jo = new JSONObject(json).optJSONObject("data");
                JSONArray array = jo.optJSONArray("list");
                if (array == null) {
                    if (jo.optInt("has_next") == 0) {
                        System.err.println("page over");
                        break;
                    }
                    Thread.sleep(4000);
                    i--;
                    continue;
                }
                for (int j = 0; j < array.length(); j++) {
                    JSONObject listItem = array.getJSONObject(j);
                    String playUrl = listItem.getString("playUrl");
                    person = new Person();
                    person.setVod_cid(listItem.optString("channelId"));
                    person.setVod_name(listItem.optString("name"));
                    float score = 0;
                    if (listItem.has("score")) {
                    	score = listItem.getFloat("score");
    				}else {
    					System.err.println("no score:"+listItem.toString());
    				}
                    int videoCount = listItem.getInt("videoCount");
                    String actor = getActor(listItem);
                    person.setScore(score);
                    person.setVideoCount(videoCount);
                    person.setVod_actor(actor);
                    getFirstInfo(playUrl);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void getFirstInfo(String playUrl) {
        try {
            Document doc = Jsoup.parse(new URL(playUrl), 30*1000);
            String pageInfo = Xsoup.select(doc, "//div[@is='i71-play-ab']/@:page-info").get();
            String videoInfo = Xsoup.select(doc, "//div[@is='i71-play-ab']/@:video-info").get();
            JSONArray category = new JSONObject(videoInfo).optJSONArray("categories");
            Map<String, String> map = getInfo(category);
            String type = map.get("类型");
            String area = map.get("地区");
            String language = map.get("语种");
            
            person.setVod_area(area);
            person.setVod_language(language);
            person.setVod_type(type);
            
            System.out.println("title size:"+pageInfo);
            JSONObject jo = new JSONObject(pageInfo);
            String albumUrl = jo.optString("albumUrl");
            albumUrl = getAbsUrl(albumUrl);
            getAllPage(albumUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getAllPage(String albumUrl) {
        try {
            System.out.println("albumUrl:"+albumUrl);
            Document doc = Jsoup.parse(new URL(albumUrl), 30*1000);
            String json = Xsoup.select(doc, "//input[@id='album-avlist-data']/@value").get();
            /*String links = Xsoup.select(doc, "//li[@data-albumlist-elem='playItem']//a/@href").get();
            String titles = Xsoup.select(doc, "//li[@data-albumlist-elem='playItem']//a/@title").get();
            String imgs = Xsoup.select(doc, "//li[@data-albumlist-elem='playItem']//a/img/@data-jpg-img").get();*/
            JSONObject jo = new JSONObject(json);
            int part = jo.optInt("part");
            JSONArray array = jo.optJSONArray("epsodelist");
            StringBuilder reUrls = new StringBuilder();
            for (int i = 0; i < array.length(); i++) {
            	
            	JSONObject item = array.getJSONObject(i);
            	String playUrl = item.getString("playUrl");
            	if (i == 0) {
                    reUrls.append(playUrl);
                    
                    String tvId = item.optString("tvId");
                    String desc = item.optString("description");
                    String thumb = item.optString("imageUrl");
                    String duration = item.optString("duration");
                    Thread.sleep(500);
                    String imageSize = item.optJSONArray("imageSize").toString().replace("[", "").replace("]", "").replace("\"", "");
                    String filmTime = item.optString("period");
                    String focus = item.optString("focus");
                    
                    person.setVod_id(tvId);
                    person.setVod_title(focus);
                    
                    person.setVod_pic(thumb);
                    int seconds = SpringJDBCTest.getDuration(duration);
                    person.setVod_length(seconds);
                    person.setVod_content(desc);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    				long date = sdf.parse(filmTime).getTime();
                    person.setFilmtime(new java.sql.Date(date));
                    person.setImageSize(imageSize);
                    person.setVod_year(filmTime.substring(0,filmTime.indexOf("-")));
                    person.setVod_director(getDirector(item));
				}else {
					reUrls.append(","+playUrl);
                    person.setVod_reurl(reUrls.toString());
				}
            }
            personService.save(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static String getDirector(JSONObject item) {
		JSONArray directorArr = item.optJSONObject("people").optJSONArray("director");
		StringBuilder director = new StringBuilder();
		if (directorArr != null) {
			for (int i = 0; i < directorArr.length(); i++) {
				String name = directorArr.getJSONObject(i).getString("name");
				if (director.length() == 0) {
					director.append(name);
				}else {
					director.append(","+name);
				}
			}
		}
		return director.toString();
	}
    private static String getActor(JSONObject item) {
		StringBuilder actorSb = new StringBuilder();
		JSONArray actorArr = item.optJSONObject("people").optJSONArray("main_charactor");
		if (actorArr != null) {
			for (int j = 0; j < actorArr.length(); j++) {
				String actorName = actorArr.getJSONObject(j).getString("name");
				if (j == 0) {
					actorSb.append(actorName);
				}else {
					actorSb.append(","+actorName);
				}
			}
		}
		return actorSb.toString();
	}
    private String getAbsUrl(String url){
        if (url.startsWith("//")){
            url = "https:"+url;
        }
        return url;
    }
    private static Map<String, String> getInfo(JSONArray category) {
		Map<String, String> map = new HashMap<>();
		JSONArray categories = category;
		if (categories != null) {
			for (int i = 0; i < categories.length(); i++) {
				JSONObject jo = categories.getJSONObject(i);
				String subName = jo.optString("subName");
				String name = jo.optString("name");
				if (map.get(subName) != null) {
					map.put(subName, map.get(subName)+","+name);
				}else {
					map.put(subName, name);
				}
			}
		}
		return map;
	}
    
}